<script setup>
import { ElMessage } from 'element-plus'
import { reactive, useTemplateRef, watch } from 'vue'

const show = defineModel('show', { type: Boolean, default: false })
const emits = defineEmits(['success'])
const props=defineProps({
  editData:{
    type:[null,Object],
    default:null
  }
})

const formRules = {
  name: [{ required: true, message: '请输入等级名称', trigger: 'blur' }]
}
const formState = reactive({
  name: '',
  isDividend: false
})
const formRef = useTemplateRef('formRef')
async function handleConfirm() {
  formRef.value.validate()
  let res=null
  if(props.editData){
    res=await window.api.updateDealerLevel(props.editData.dealer_level_id,formState.name, formState.isDividend ? 1 : 0)
  }else{
    res = await window.api.insertDealerLevel(formState.name, formState.isDividend ? 1 : 0)
  }
  if(res==='等级名称重复'){
    ElMessage.warning('等级名称不可重复')
    return
  }
  if (res > 0) {
    ElMessage.success('保存成功')
    emits('success')
    formState.name = ''
    formState.isDividend = false
    show.value = false
  }
}

watch(
  ()=>show.value,
  (n)=>{
    if(n&&props.editData){
      formState.name=props.editData.dealer_level_name
      formState.isDividend=props.editData.is_dividend?true:false
    }
  }
)

</script>

<template>
  <el-dialog v-model="show" width="500" :title="props.editData?'编辑等级':'创建等级'" draggable>
    <el-form ref="formRef" :model="formState" :rules="formRules" label-width="100px">
      <el-form-item label="等级名称" prop="name">
        <el-input v-model="formState.name" maxlength="8" placeholder="请输入等级名称" />
      </el-form-item>
      <el-form-item label="是否分红" prop="isDividend">
        <el-switch v-model="formState.isDividend"></el-switch>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="show = false">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>
